package com.itheima.server.service;

import com.itheima.commons.utils.JwtUtils;
import com.itheima.server.exception.BusinessException;
import com.itheima.tanhua.autoconfig.template.SmsTemplate;
import com.itheima.tanhua.dubbo.api.UserApi;
import com.itheima.tanhua.model.vo.ErrorResult;
import com.itheima.tanhua.model.domain.User;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @DubboReference
    private UserApi userApi;

    /**
     * 发送短信验证码
     *
     * @param phone
     */
    public void sendMsg(String phone) {

        //随机生成6位随机数
        //String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        //调用SmsTemplate对象，发送短信验证码
        // smsTemplate.sendSms(phone,code);

        //将生成的验证码存入到缓存redis中

        //设置缓存失效时间的两种方法
        redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

//        redisTemplate.opsForValue().set(phone,code,Duration.ofMinutes(5));
    }

    public Map loginVerification(String phone, String code) {


        //获取缓存中的验证码
        String redisCode = (String) redisTemplate.opsForValue().get(phone);


//        System.out.println(redisCode);
//
//        System.out.println(code);

        //判断输入的验证码与缓存的验证码是否一致
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            throw new BusinessException(ErrorResult.loginError());
        }
        //删除缓存
        redisTemplate.delete(phone);

        //查询该手机号是否存在
        User user = userApi.findByPhone(phone);

        boolean isNew = false;

        //如果收集号不存在，则创建新用户
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            user.setCreated(new Date());
            user.setUpdated(new Date());

            Long userId = userApi.save(user);
            user.setId(userId);

            isNew = true;
        }

        //通过JWT生成token
        Map tMap = new HashMap();
        tMap.put("userId", user.getId());
        tMap.put("phone", phone);
        String token = JwtUtils.getToken(tMap);

        //构造返回值,isNew  token

        Map resMap = new HashMap();
        resMap.put("token", token);
        resMap.put("isNew", isNew);

        return resMap;
    }
}
